package 纯数组;

import com.alibaba.fastjson.JSON;

public class JZ29顺时针打印矩阵 {

    /**
     * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
     *
     * 示例 1：
     * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
     * 输出：[1,2,3,6,9,8,7,4,5]
     * 示例 2：
     * 输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
     * 输出：[1,2,3,4,8,12,11,10,9,5,6,7]
     *  
     * 限制：
     * 0 <= matrix.length <= 100
     * 0 <= matrix[i].length <= 100
     */

    private int allLength;
    private int itemLength;
    private int[] result;
    private int[][] matrix;

    public int[] spiralOrder(int[][] matrix) {

        if(matrix.length==0||matrix[0].length==0){
            return new int[]{};
        }

        this.allLength=matrix.length;
        this.itemLength=matrix[0].length;
        this.result=new int[allLength*itemLength];
        this.matrix =matrix;
        this.spiralOrder();
        return result;
    }

    private void spiralOrder() {
        int top=0;
        int left=0;
        int right=itemLength-1;
        int bottom=allLength-1;
        int x=0;
        int y=0;
        int index=0;


        while (true){

            //左->右
            for (; x <= right; x++) {
                result[index++]= matrix[y][x];
            }
            x--;
            y++;
            right--;
            top++;

            if(index==result.length){
                break;
            }

            //右->下
            for (; y <= bottom; y++) {
                result[index++]= matrix[y][x];
            }
            y--;
            x--;
            bottom--;

            if(index==result.length){
                break;
            }

            //下->左
            for (; x>=left; x--) {
                result[index++]= matrix[y][x];
            }
            x++;
            y--;
            left++;

            if(index==result.length){
                break;
            }

            //左->上
            for(; y>=top; y--){
                result[index++]= matrix[y][x];
            }
            y++;
            x++;

            if(index==result.length){
                break;
            }

        }

    }

    public static void main(String[] args) {
        JZ29顺时针打印矩阵 jz=new JZ29顺时针打印矩阵();
        int[][] arr={{1,2,3},{4,5,6},{7,8,9}};
        int[] result = jz.spiralOrder(arr);
        System.out.println(JSON.toJSONString(result));
    }

}
